import React, {useState, useEffect, useRef} from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch, faTimes } from '@fortawesome/free-solid-svg-icons'
import PropTypes from 'prop-types'

const FileSearch = ({title, onFileSearch}) => {
  const [inputActive, setInputActive] = useState(false);
  const [value, setValue] = useState('');

  let node = useRef(null) 
  
  const closeSearch = (e) => {
    e.preventDefault()
    setInputActive(false)
    setValue('')
  }

  const handleInputEvent = (event) => {
    const {keyCode} = event;
    // console.log('keyCode', keyCode, inputActive)
    if(keyCode === 13 && inputActive) {
      onFileSearch(value)
    } else if(keyCode === 27 && inputActive) {
      closeSearch(event)
    }
  }

  useEffect(() => {
    document.addEventListener('keyup', handleInputEvent)
    return () => {
      document.removeEventListener('keyup', handleInputEvent)
    }
  }, [inputActive, value]);

  useEffect(() => {
    inputActive && node.current.focus()

  }, [inputActive]);

  return (
    <div className='alert alert-primary'>
      {!inputActive && 
        <div className='d-flex justify-content-between align-items-center'>
          <span>{title}</span>
          <button 
            type='button' 
            className='icon-button' 
            onClick={() => setInputActive(true)}
          >
            <FontAwesomeIcon icon={faSearch} title='搜索' size='lg' />
          </button>
        </div>
      }
      {
        inputActive && 
        <div className='d-flex justify-content-between align-items-center'>
          <input 
            className='form-control'
            placeholder='输入内容 回车搜索' 
            value={value}
            onChange={(e) => {setValue(e.target.value)}}
            ref={node}
            />
          <button 
            type='button' 
            className='icon-button' 
            onClick={closeSearch}
          >
            <FontAwesomeIcon icon={faTimes} title='关闭' size='lg' />
          </button>  
        </div>
      }
    </div>
  )
}

// 属性检查
FileSearch.propTypes = {
  title: PropTypes.string,
  onFileSearch: PropTypes.func.isRequired,
}
FileSearch.defaultProps = {
  title: '我的云文档'
}
export default FileSearch